package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by Administrator on 2017/10/13.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomerUserService customerUserService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles("ROLE_ADMIN")
                .and()
                .withUser("yy").password("yy").roles("ROLE_USER");
        auth.userDetailsService(customerUserService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()//通过authorizeRequests方法来开始请求权限配置
                .antMatchers("/admin/**").hasRole("ROLE_ADMIN")//请求匹配/admin/**，只有拥有ROLE_ADMIN角色的用户可以访问
                .antMatchers("/user/**").hasAnyRole("ROLE_ADMIN","ROLE_USER")//请求匹配/user/**，拥有ROLE_ADMIN或ROLE_USER角色的用户都可以访问
                .anyRequest().authenticated();//其余所欲的请求都需要认证后（登陆后）才可访问

    }
}
